import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用黑体显示中文
plt.rcParams['axes.unicode_minus'] = False    # 正常显示负号

# 参数化圆周 |z| = 2
# z(t) = 2 * exp(i*t), t in [0, 2*pi]
def circle_path(t, radius=2):
    return radius * np.exp(1j * t)

def derivative_circle_path(t, radius=2):
    return 1j * radius * np.exp(1j * t)

# 被积函数 f(z) = 1/(z^2 - 1)
def integrand(z):
    return 1 / (z**2 - 1)
    # return 1 / (z**2 - 2*z -3)

# 数值积分
def complex_contour_integral(radius=2, n_points=100):
    t = np.linspace(0, 2*np.pi, n_points)
    z = circle_path(t, radius)
    dz = derivative_circle_path(t, radius) * (t[1] - t[0])
    
    integral = np.sum(integrand(z) * dz)
    return integral

# 计算积分
result = complex_contour_integral(radius=2)
print(f"沿|z|=2的积分值: {result:.4f}")

# 解析解：函数 1/(z^2-1) = 1/((z-1)(z+1)) 在|z|=2内部有极点 z=1, z=-1
# 使用留数定理：
# Res(f,1) = lim_{z->1}(z-1)f(z) = lim_{z->1} 1/(z+1) = 1/2
# Res(f,-1) = lim_{z->-1}(z+1)f(z) = lim_{z->-1} 1/(z-1) = -1/2
# 积分 = 2*pi*i * (1/2 - 1/2) = 0
analytical_result = 0 + 0j
print(f"解析解 (留数定理): {analytical_result:.4f}")
print(f"误差: {abs(result - analytical_result):.4f}")

# 可视化路径
t_plot = np.linspace(0, 2*np.pi, 100)
z_plot = circle_path(t_plot, 2)
plt.figure(figsize=(8, 8))
plt.plot(np.real(z_plot), np.imag(z_plot), label='积分路径 $|z|=2$')
plt.scatter([-1, 1], [0, 0], color='red', s=100, label='极点 $z=-1$, $z=1$')
plt.xlabel('实部')
plt.ylabel('虚部')
plt.xlim(-3,3)
plt.ylim(-3,3)
plt.xticks(range(-3, 4))  # -3, -2, ..., 3
plt.yticks(range(-3, 4))
plt.title('复积分路径')
plt.grid(True)
# plt.axis('equal')
plt.legend(loc='upper right')
plt.show()
